/**
 * Copyright 2004 - 2007 Blue Bamboo International Inc. 
 *           All rights reserved.
 *
 *
 * Blue Bamboo PROPRIETARY/CONFIDENTIAL.
 *
 */

package com.bambamboo.st;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

/**
 * The main entry to startup TCP server
 * 
 * @author Nick.Tan
 * @since 1.0.0
 */
public class Server {

	private static final Logger logger = LoggerFactory.getLogger(Server.class);
	private ApplicationContext appCtx;

	public static void main(String[] args) {
		Server server = new Server();
		server.initialize(args);
		try {
			server.startup();
		}
		catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	public void initialize(String[] args) {
		appCtx = new FileSystemXmlApplicationContext("./config/applicationContext.xml");
	}

	public void startup() throws Exception {
		Map<String, AbstractIOServer> beans = appCtx.getBeansOfType(AbstractIOServer.class);
		logger.info("================== starting server ... ==================");
		for (Map.Entry<String, AbstractIOServer> entry : beans.entrySet()) {
			AbstractIOServer server = entry.getValue();
			ConnectionBean bean = server.getConnectionBean();
			if (bean.isEnable() == false) {
				logger.info(">>> server configuration disabled: " + bean);
				continue;
			}

			server.setConnectionBean(bean);

			try {
				server.startup();
				logger.info(">>> listening on {} port [{}]", server.getType(), bean.getName());
				logger.info("\t\thandler: {}", bean.getProcessor());
			}
			catch (Exception e) {
				// catch to continue binding other ports
				logger.error(String.format(">>> start server on %s port [%s] failure!", server.getType(), bean
						.getName()), e);
			}
		}
		logger.info("================== server started ==================");
	}
}
